import os
import sys
import urllib
import re
import string
from md5 import md5
from datetime import datetime
import logging

from google.appengine.ext import db

import AppEnv
    
__unsafeTag__ = ['iframe',
                 'title',
                 'frame',
                 'frameset',
                 'object',
                 'script',
                 'embed',
                 'applet',
                 'meta',
                 '!doctype',
                 'link',
                 'body',
                 'head',
                 ]
__unsafePattern__ = []
for tag in __unsafeTag__:
    __unsafePattern__.append(re.compile('<%s.*?>' % tag, re.I|re.M|re.S))

def stripUnsafeTag(string):
    for p in __unsafePattern__:
        string = p.sub('', string)
    return string

def deleteAllModels(*args):
    for model in args:
        while True:
            ms = model.all().fetch(limit=1000)
            if not ms:
                break
            for m in ms:
                m.delete()

def urlString2uid(uid):
    return uid

def urlString2PageString(tag):
    tag = urllib.unquote_plus(tag)
    tag = urllib.unquote_plus(tag)
    return toPageString(tag)

def pageString2UrlString(tag):
    return urllib.quote_plus(toPageString(tag))

def toDBString(s):
    """convert to string to store in db.(Unicode)
    s is encoded in utf-8 in current system
    """
    if isinstance(s,unicode):
        return s
    return unicode(s, AppEnv.appencoding)

def toDBText(s):
    """Convert to db.Text to store in db.(Unicode)
    s is encoded in utf-8 in current system.

    Args:
        s: str to convert.

    Returns:
        A db.Text object
    """
    if isinstance(s,unicode):
        return s
    return db.Text(s, encoding=AppEnv.appencoding)

def toPageString(s):
    """Convert Unicode string s to encoded string using
    in page.Current encoding is utf-8.

    Args:
        s: Unicode string to convert.

    Returns:
        Converted utf-8 string
    """
    if isinstance(s,unicode):
        return s.encode(AppEnv.appencoding)
    return s
    
def getPasswordHash(username,password):
    return md5(username + AppEnv.md5salt + password).hexdigest()

def getRandomPass():
    from random import randint
    charstring = string.ascii_letters[:] + string.digits[:] + string.punctuation[:] + string.digits[:] + string.ascii_letters[:]
    return ''.join(charstring[randint(0,len(charstring)-1)] for i in range(10))

def format_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

def addMonth(dt):
    if dt.month==12:
        edt = datetime(dt.year+1,1,dt.day)
    else:
        edt = datetime(dt.year,dt.month+1,dt.day)
    return edt

